<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
<head>
<title>Components</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="GUI, Components, Swing, JRuby, programming, Linux">
<meta name="description" content="This chapter of the JRuby Swing tutorial covers several
Swing components.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Components</h1>

<p>
In this part of the JRuby Swing programming tutorial, we will cover
basic Swing components. 
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 


<p>
Components are basic building blocks of a GUI application. Over the years, 
several components became a standard in all toolkits on all OS platforms. 
For example a button, a check box or a scroll bar. 
Swing has a rich set of components which covers most of the programming needs.
More specialized components can be created as custom components. 
</p>


<h2>JCheckBox</h2>

<p>
The <code>JCheckBox</code> is a component, that has two states. On and Off. 
The On state is visualized by a check mark. It is used to denote some boolean property. 
The JCheckBox component provides a check box with a text label.
</p>

<pre class="code">
#!/usr/local/bin/jruby

# ZetCode JRuby Swing tutorial
#
# This program uses JCheckBox
# component to show/hide the title
# of the window
#
# author: Jan Bodnar
# website: www.zetcode.com
# last modified: December 2010

include Java

import java.awt.Dimension
import javax.swing.JCheckBox
import javax.swing.Box
import javax.swing.BoxLayout
import javax.swing.JFrame


class Example &lt; JFrame
  
    def initialize
        super "JCheckBox example"
        
        self.initUI
    end
      
    def initUI
      
        self.setLayout BoxLayout.new getContentPane, BoxLayout::Y_AXIS
        self.add Box.createRigidArea Dimension.new 15, 20

        cb = JCheckBox.new "Show Title", true
        cb.setBounds 50, 60, 80, 30
        cb.setFocusable(false)

            
        cb.add_action_listener do |e|
            if self.getTitle.empty?
                self.setTitle "JCheckBox example"
            else
                self.setTitle ""
            end
        end
        
        add cb
        
        self.setDefaultCloseOperation JFrame::EXIT_ON_CLOSE
        self.setSize 300, 200
        self.setLocationRelativeTo nil
        self.setVisible true
    end
end

Example.new
</pre>

<p>
In our example, we place a check box on the window. The check 
box shows/hides the title of the window. 
</p>

<pre class="explanation">
self.setLayout BoxLayout.new getContentPane, BoxLayout::Y_AXIS
self.add Box.createRigidArea Dimension.new 15, 20
</pre>

<p>
In this example, we use a <code>BoxLayout</code> layout manager. We put some space 
there, so that the check box is not too close to the corner.
</p>

<pre class="explanation">
cb = JCheckBox.new "Show Title", true
</pre>

<p>
The <code>JCheckBox</code> component is created. The first
parameter of the constructor is its text label. The second parameter
is a  boolean value indicating the initial selection state. 
If true the check box is selected. 
</p>


<pre class="explanation">
cb.setFocusable false
</pre>

<p>
We disable the focus for the check box. A <code>JCheckBox</code> that has a focus may
be selected or unselected with a spacebar. 
</p>

<pre class="explanation">
cb.add_action_listener do |e|
    if self.getTitle.empty?
        self.setTitle "JCheckBox example"
    else
        self.setTitle ""
    end
end
</pre>

<p>
Inside the action listener, we check if the title is set.
If there is a title, we remove it. If there is no title, we
set one. This way we toggle the visibility of a title.
</p>


<img src="/img/gui/jythonswing/jcheckbox.png" alt="JCheckBox">
<div class="figure">Figure: JCheckBox</div>


<h2>JLabel</h2>

<p>
The <code>JLabel</code> component is used to display text, image or
both. No user interaction is available.
</p>

<pre class="code">
#!/usr/local/bin/jruby

# ZetCode JRuby Swing tutorial
#
# In this program, we show lyrics of a
# song in a window.
#
# author: Jan Bodnar
# website: www.zetcode.com
# last modified: December 2010


include Java

import java.awt.BorderLayout
import java.awt.Color
import java.awt.Font

import javax.swing.JFrame
import javax.swing.BorderFactory
import javax.swing.JPanel
import javax.swing.JLabel


class Example &lt; JFrame
  
    def initialize
        super "Lyrics"
        
        self.initUI
    end
      
    def initUI
      
        lyrics =  "&lt;html&gt;It's way too late to think of&lt;br&gt;
        Someone I would call now&lt;br&gt;
        And neon signs got tired&lt;br&gt;
        Red eye flights help the stars out&lt;br&gt;
        I'm safe in a corner&lt;br&gt;
        Just hours before me&lt;br&gt;
        &lt;br&gt;
        I'm waking with the roaches&lt;br&gt;
        The world has surrendered&lt;br&gt;
        I'm dating ancient ghosts&lt;br&gt;
        The ones I made friends with&lt;br&gt;
        The comfort of fireflies&lt;br&gt;
        Long gone before daylight&lt;br&gt;
        &lt;br&gt;
        And if I had one wishful field tonight&lt;br&gt;
        I'd ask for the sun to never rise&lt;br&gt;
        If God leant his voice for me to speak&lt;br&gt;
        I'd say go to bed, world&lt;br&gt;
        &lt;br&gt;
        I've always been too late&lt;br&gt;
        To see what's before me&lt;br&gt;
        And I know nothing sweeter than&lt;br&gt;
        Champaign from last New Years&lt;br&gt;
        Sweet music in my ears&lt;br&gt;
        And a night full of no fears&lt;br&gt;
        &lt;br&gt;
        But if I had one wishful field tonight&lt;br&gt;
        I'd ask for the sun to never rise&lt;br&gt;
        If God passed a mic to me to speak&lt;br&gt;
        I'd say stay in bed, world&lt;br&gt;
        Sleep in peace&lt;/html&gt;"

        panel = JPanel.new
        panel.setLayout BorderLayout.new 10, 10

        label = JLabel.new lyrics
        label.setFont Font.new "Georgia", Font::PLAIN, 14
        label.setForeground Color.new 50, 50, 25

        panel.add label, BorderLayout::CENTER
        panel.setBorder BorderFactory.createEmptyBorder 10, 10, 10, 10
        self.add panel
        self.pack
      
        self.setDefaultCloseOperation JFrame::EXIT_ON_CLOSE
        self.setLocationRelativeTo nil
        self.setVisible true
    end    
end

Example.new
</pre>

<p>
Our example shows lyrics of a song in the window. We can use HTML 
tags in <code>JLabel</code> component. We use the &lt;br&gt; tag to separate lines.
</p>

<pre class="explanation">
lyrics =  "&lt;html&gt;It's way too late to think of&lt;br&gt;
Someone I would call now&lt;br&gt;
And neon signs got tired&lt;br&gt;
...
</pre>

<p>
We define a multi line text. 
</p>

<pre class="explanation">
label = JLabel.new lyrics
label.setFont Font.new "Georgia", Font::PLAIN, 14
</pre>

<p>
Here we create the label component. We set its font to plain 
Georgia, 14px tall. 
</p>

<pre class="explanation">
panel.add label, BorderLayout::CENTER
panel.setBorder BorderFactory.createEmptyBorder 10, 10, 10, 10
</pre>

<p>
We put the label into the center of the panel. We put 10px around the label.
</p>

<img src="/img/gui/jythonswing/nosleep.png" alt="JLabel component">
<div class="figure">Figure: JLabel component</div>


<h2>JSlider</h2>

<p>
<code>JSlider</code> is a component that lets the user 
graphically select a 
value by sliding a knob within a bounded interval. 
Our example will show a volume control.
</p>

<pre class="code">
#!/usr/local/bin/jruby

# ZetCode JRuby Swing tutorial
#
# In this program we use a JSlider
# component to control volume images.
#
# author: Jan Bodnar
# website: www.zetcode.com
# last modified: December 2010


include Java

import java.awt.Dimension
import java.awt.BorderLayout

import javax.swing.event.ChangeListener
import javax.swing.JFrame
import javax.swing.JSlider
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.BorderFactory
import javax.swing.Box
import javax.swing.BoxLayout
import javax.swing.ImageIcon


class ChangeEvent
    include ChangeListener
    
    def setLabel label
        @label = label
    end    

    def setIcons mute, min, med, max
        @mute = mute
        @min = min
        @med = med
        @max = max
    end       
                
    
    def stateChanged e
        sender = e.getSource
         
        value = sender.getValue

        if value == 0
            @label.setIcon(@mute)
        elsif value > 0 and value <= 30
            @label.setIcon(@min)
        elsif value > 30 and value < 80
            @label.setIcon(@med)
        else
            @label.setIcon(@max)  
        end            
    end    
end



class Example < JFrame
  
    def initialize
        super "JSlider"
        
        self.initUI
    end
      
    def initUI
      
        mute = ImageIcon.new "mute.png"
        min = ImageIcon.new "min.png"
        med = ImageIcon.new "med.png"
        max = ImageIcon.new "max.png"

        panel = JPanel.new
        panel.setLayout BoxLayout.new panel, BoxLayout::X_AXIS
        panel.setBorder BorderFactory.createEmptyBorder 40, 40, 40, 40
        self.setLayout BorderLayout.new

        panel.add Box.createHorizontalGlue

        label = JLabel.new mute, JLabel::CENTER
                
        slider = JSlider.new 0, 150, 0
        
        ce = ChangeEvent.new
        ce.setLabel label
        ce.setIcons mute, min, med, max
        slider.add_change_listener ce
        
        slider.setPreferredSize Dimension.new 150, 30

        panel.add slider
        panel.add label
        panel.add Box.createRigidArea Dimension.new 5, 0
        
        panel.add Box.createHorizontalGlue
        self.add panel, BorderLayout::CENTER

        self.pack
        
        self.setDefaultCloseOperation JFrame::EXIT_ON_CLOSE
        self.setSize 300, 200
        self.setLocationRelativeTo nil
        self.setVisible true
    end
end

Example.new
</pre>

<p>
In the code example, we show a <code>JSlider</code> and a <code>JLabel</code>. 
By dragging the slider, we change the icon on the label component. We
have four images that represent various states of the sound. 
</p>

<pre class="explanation">
mute = ImageIcon.new "mute.png"
</pre>

<p>
Here we create an image icon.
</p>

<pre class="explanation">
panel.setLayout BoxLayout.new panel, BoxLayout::X_AXIS
</pre>

<p>
Panel component has a horizontal <code>BoxLayout</code>.
</p>

<pre class="explanation">
panel.setBorder BorderFactory.createEmptyBorder 40, 40, 40, 40
</pre>

<p>
We creare a 40px border around the panel.
</p>

<pre class="explanation">
panel.add Box.createHorizontalGlue
</pre>

<p>
We put resizable space to both sides, left and right. It 
is to prevent <code>JSlider</code> from growing to unnatural sizes.
</p>

<pre class="explanation">
label = JLabel.new mute, JLabel::CENTER
</pre>

<p>
This line creates a <code>JLabel</code> instance with the specified image 
and horizontal alignment. The label is centered vertically in its display area by
default.
</p>

<pre class="explanation">
slider = JSlider.new 0, 150, 0
</pre>

<p>
This is a <code>JSlider</code> constructor. The parameters are 
minimum value, maximum value and current value. 
</p>

<pre class="explanation">
ce = ChangeEvent.new
ce.setLabel label
ce.setIcons mute, min, med, max
</pre>

<p>
A ChangeEvent object is created. We set a label and icons to this
object. 
</p>

<pre class="explanation">
slider.add_change_listener ce
</pre>

<p>
Each time we move the slider, the <code>stateChanged</code> method
of the ChangeEvent object will be called.
</p>

<pre class="explanation">
panel.add Box.createRigidArea Dimension.new 5, 0
</pre>

<p>
We place a 5px rigid space between the two components. 
They are too close to each other, when the slider is at the end position.
</p>

<pre class="explanation">
class ChangeEvent
    include ChangeListener
</pre>

<p>
This is a ChangeEvent class, which implements the <code>ChangeListener</code>.
As a consequence, this class must implement a <code>changeEvent</code> method.
</p>

<pre class="explanation">
sender = e.getSource
  
value = sender.getValue
</pre>

<p>
Inside the <code>changeEvent</code> method, we get the event
source. It is the slider, which has generated the event. 
From the sender, we get the current value. 
</p>

<pre class="explanation">
if value == 0
    @label.setIcon(@mute)
</pre>

<p>
If the value is equal to zero, we update the label to have
a mute.png image.
</p>

<img src="/img/gui/jythonswing/jslider.png" alt="JSlider">
<div class="figure">Figure: JSlider</div>


<h2>JToggleButton</h2>

<p>
<code>JToggleButton</code> is a button that has two states. 
Pressed and not pressed. You toggle between these two states 
by clicking on it. There are situations where this 
functionality fits well.
</p>

<pre class="code">
#!/usr/local/bin/jruby

# ZetCode JRuby Swing tutorial
#
# This program uses toggle buttons to
# change the background color of
# a panel.
#
# author: Jan Bodnar
# website: www.zetcode.com
# last modified: December 2010

include Java

import java.awt.Color
import java.awt.Dimension
import java.awt.event.ActionListener
import javax.swing.JToggleButton
import javax.swing.Box
import javax.swing.BoxLayout
import javax.swing.BorderFactory
import javax.swing.JFrame
import javax.swing.JPanel
import javax.swing.border.LineBorder


class Example &lt; JFrame
    include ActionListener
    
    def initialize
        super "JToggleButton"
        
        self.initUI
    end
      
    def initUI
      
        self.setPreferredSize Dimension.new 280, 200

        bottom = JPanel.new
        bottom.setLayout BoxLayout.new bottom, BoxLayout::X_AXIS
        bottom.setBorder BorderFactory.createEmptyBorder 20, 20, 20, 20

        leftPanel = JPanel.new
        leftPanel.setLayout BoxLayout.new leftPanel, BoxLayout::Y_AXIS

        @display = JPanel.new
        @display.setPreferredSize Dimension.new 110, 110
        @display.setBorder LineBorder.createGrayLineBorder
        @display.setBackground Color.black

        bottom.add @display
            
        redButton = JToggleButton.new "red"
        redButton.addActionListener self
        greenButton = JToggleButton.new "green"
        greenButton.addActionListener self
        blueButton = JToggleButton.new "blue"
        blueButton.addActionListener self
        

        blueButton.setMaximumSize greenButton.getMaximumSize
        redButton.setMaximumSize greenButton.getMaximumSize

        leftPanel.add redButton
        leftPanel.add Box.createRigidArea Dimension.new 25, 7
        leftPanel.add greenButton
        leftPanel.add Box.createRigidArea Dimension.new 25, 7
        leftPanel.add blueButton      

        bottom.add leftPanel
        bottom.add Box.createRigidArea Dimension.new 20, 0

        self.add bottom
        self.pack
      
        self.setDefaultCloseOperation JFrame::EXIT_ON_CLOSE
        self.setSize 300, 200
        self.setLocationRelativeTo nil
        self.setVisible true
    end
    
    def actionPerformed e
                
        color = @display.getBackground
        red = color.getRed
        green = color.getGreen
        blue = color.getBlue

        if e.getActionCommand == "red"
            if red == 0
                red = 255
            else
                red = 0
            end
        end

        if e.getActionCommand == "green"
            if green == 0
                green = 255
            else
                green = 0
            end
        end

        if e.getActionCommand == "blue"
            if blue == 0
                blue = 255
            else
                blue = 0
            end            
        end

        setCol = Color.new red, green, blue
        @display.setBackground setCol        
    end      
end

Example.new
</pre>

<p>
In the code example, we use three toggle buttons to change the color
of a rectangular component. 
</p>

<pre class="explanation">
class Example &lt; JFrame
    include ActionListener
</pre>

<p>
The class implements the <code>ActionListener</code>. We will do some action
in the <code>actionPerformed</code> method of the Example class.
</p>

<pre class="explanation">
redButton = JToggleButton.new "red"
redButton.addActionListener self
</pre>

<p>
We create a <code>JToggleButton</code> component. We add an action
listener to the button. The action listener is the Example class. 
When we click on the redButton, the <code>actionPerformed</code> method of the
Example class will be called.
</p>

<pre class="explanation">
blueButton.setMaximumSize greenButton.getMaximumSize
redButton.setMaximumSize greenButton.getMaximumSize
</pre>

<p>
We make all three buttons of equal size.
</p>

<pre class="explanation">
color = @display.getBackground
red = color.getRed
green = color.getGreen
blue = color.getBlue
</pre>

<p>
We determine the current red, green, blue parts of the display background color.
</p>

<pre class="explanation">
if e.getActionCommand == "red"
    if red == 0
        red = 255
    else
        red = 0
    end
end
</pre>

<p>
We determine, which button was toggled, and update the color part of 
the RGB value accordingly.
</p>

<pre class="explanation">
setCol = Color.new red, green, blue
@display.setBackground setCol
</pre>

<p>
Here a new color is created and the display panel is updated to a new color.
</p>

<img src="/img/gui/jythonswing/jtogglebutton.png" alt="JToggleButton">
<div class="figure">Figure: JToggleButton</div>


<h2>JList</h2>

<p>
<code>JList</code> is a component that displays a list of objects. It allows the user 
to select one or more items.
</p>

<pre class="code">
#!/usr/local/bin/jruby

# ZetCode JRuby Swing tutorial
#
# In this program, we show all 
# available fonts of a system in 
# a JList component.
#
# author: Jan Bodnar
# website: www.zetcode.com
# last modified: December 2010

include Java


import java.awt.BorderLayout
import java.awt.Dimension
import java.awt.Font
import java.awt.GraphicsEnvironment

import javax.swing.JFrame
import javax.swing.BorderFactory
import javax.swing.JScrollPane
import javax.swing.JPanel
import javax.swing.JLabel
import javax.swing.JList


class Example < JFrame
  
  def initialize
    super "JList"
    
    initUI
  end
    
  def initUI
    
    panel = JPanel.new
    panel.setLayout BorderLayout.new
    panel.setBorder BorderFactory.createEmptyBorder 20, 20, 20, 20

    ge = GraphicsEnvironment.getLocalGraphicsEnvironment
    fonts = ge.getAvailableFontFamilyNames

    list = JList.new fonts

    list.add_list_selection_listener do |e|

        sender = e.source

        if not e.getValueIsAdjusting
            name = sender.getSelectedValue
            font = Font.new name, Font::PLAIN, 13
            @label.setFont font
        end
    end

    pane = JScrollPane.new
    pane.getViewport.add list
    pane.setPreferredSize Dimension.new 250, 200
    panel.add pane

    @label = JLabel.new "Aguirre, der Zorn Gottes"
    @label.setFont Font.new "Serif", Font::PLAIN, 12
    self.add @label, BorderLayout::SOUTH

    self.add panel
    self.pack
    
    self.setDefaultCloseOperation JFrame::EXIT_ON_CLOSE
    self.setLocationRelativeTo nil
    self.setVisible true
  end
    
end

Example.new
</pre>

<p>
In our example, we will display a <code>JList</code> and a <code>JLabel</code> 
components. The list component contains a list of all available font family names 
on our system. If we select an item from the list, the label will 
be displayed in a font, we have chosen.
</p>

<pre class="explanation">
ge = GraphicsEnvironment.getLocalGraphicsEnvironment
fonts = ge.getAvailableFontFamilyNames
</pre>

<p>
Here we obtain all possible font family names on our system.
</p>

<pre class="explanation">
list = JList.new fonts
</pre>

<p>
We create an instance of the <code>JList</code> component. 
It will display all font family names. 
</p>


<pre class="explanation">
if not e.getValueIsAdjusting
</pre>

<p>
Events in list selection are grouped. We receive events for both selecting 
and unselecting. To filter only the selecting events, we use the 
<code>getValueIsAdjusting</code> method.
</p>


<pre class="explanation">
name = sender.getSelectedValue
font = Font.new name, Font::PLAIN, 13
@label.setFont font
</pre>

<p>
We get the selected item and set a new font for the label.
</p>

<pre class="explanation">
pane = JScrollPane.new
pane.getViewport.add list
</pre>

<p>
<code>JList</code> component is not scrollable by default. 
We put the list into the <code>JScrollPane</code> to make 
it scrollable.
</p>

<img src="/img/gui/jythonswing/jlist.png" alt="JList component">
<div class="figure">Figure: JList component</div>


<hr class="btm">

<p>
In this part of the JRuby Swing tutorial, we have presented several Swing components.
</p>


<br>
<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 
<br>




<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified December 21, 2010  <span class="copyright">&copy; 2007 - 2012 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

